package com.hanxiaozhang.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

/**
 * 功能描述: <br>
 * 〈配置授权服务器〉
 *
 * @Author:hanxiaozhang
 * @Date: 2020/7/27
 */
@Configuration
public class Oauth2ServiceConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    /**
     * 配置客户端详情服务
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                // 客户端id
                .withClient("hanxiaozhang")
                // 允许请求范围
                .scopes("hanxiaozhang")
                // 客户端可以使用的授权范围
                .authorizedGrantTypes("password", "authorization_code", "refresh_token")
                // 客户端安全码
                .secret(new BCryptPasswordEncoder().encode("hanxiaozhang"));

    }

    /**
     * 配置Endpoints相关信息：AuthorizationServer、TokenServices、TokenStore、
     * ClientDetailsService、UserDetailsService
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.authenticationManager(authenticationManager)
                .tokenStore(jdbcTokenStore())
                .tokenServices(tokenServices());
    }

    @Primary
    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        // access_token:72个小时
        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 72);
        // refresh_token:144个小时,但是前端没有去使用
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 114);
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setReuseRefreshToken(false);
        tokenServices.setTokenStore(jdbcTokenStore());
        return tokenServices;
    }

    @Bean
    JdbcTokenStore jdbcTokenStore() {
        return new JdbcTokenStore(dataSource);
    }


    /**
     * AuthorizationServerSecurityConfigurer继承SecurityConfigurerAdapter，是一个Spring Security安全配置
     * 提供给AuthorizationServer去配置AuthorizationServer的端点（/oauth/****）的安全访问规则、过滤器Filter
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 获取token的请求不在拦截
                .tokenKeyAccess("permitAll()")
                // 验证通过返回token信息
                .checkTokenAccess("isAuthenticated()")
                //  运行客户端使用client_id和client_secret获取token
                .allowFormAuthenticationForClients();
    }


    public static void main(String[] args) {
        System.out.println("加密： " + new BCryptPasswordEncoder().encode("hanxiaozhang"));
        System.out.println("比对： " + new BCryptPasswordEncoder().matches("123456", "$2a$10$N5WQVfjpdj.v00dgkBW9cu48iKvke8fu1IsuaKRj5rOc/olmrEetW"));
        System.out.println("比对： " + new BCryptPasswordEncoder().matches("123456", "$2a$10$Vp1CxPTT/QBmU88jZYzkXOYgIq04Kvfd.o.YYqFn0y6rC5hgO/Yqe"));

    }

}
